/*
Client
*/

#define _CRT_SECURE_NO_WARNINGS

#include <stdio.h>
#include <WinSock2.h>

#pragma comment(lib, "Ws2_32.lib")

#define SERVER_PORT 23505
#define SERVER_IP inet_addr("127.0.0.1");

const int bufferSize = 32;

BOOL IsWSAStartupFailed(int wsastartupResult)
{
	return wsastartupResult != NO_ERROR;
}

void PrintLine(const char * format, ...)
{
	char lineFormat[32];
	sprintf(lineFormat, "%s\n", format);


	va_list arg;
	int done;

	va_start (arg, format);

	done = vfprintf (stdout, lineFormat, arg);

	va_end (arg);
}

void ExitWithPause(int errorCode)
{
	system("pause");
	exit(errorCode);
}

void MakeExpression(char * expression, int num1, int num2, char opr)
{
	sprintf(expression, "%d;%d;%c", num1, num2, opr);
}

int main()
{
	WSADATA wsa;
	WORD requestedVersion = MAKEWORD(2, 2);

	//wsastartup
	int wsaResult = WSAStartup(requestedVersion, &wsa);

	PrintLine("WSAStartup()...");
	if(IsWSAStartupFailed(wsaResult))
	{
		PrintLine("Error in WSAStartup()");
		ExitWithPause(1);
	}
	PrintLine("WSAStartup() done");

	//socket
	PrintLine("sock()...");
	SOCKET serverSocket = socket(AF_INET, SOCK_STREAM, 0);
	PrintLine("socket() done");

	sockaddr_in serverAddr;
	serverAddr.sin_family = AF_INET;
	serverAddr.sin_port = htons(SERVER_PORT);
	serverAddr.sin_addr.s_addr = SERVER_IP;

	//bind
	PrintLine("connect()...");
	int connectResult = connect(serverSocket, (sockaddr*)&serverAddr, sizeof(serverAddr));

	if(connectResult == SOCKET_ERROR)
	{
		PrintLine("Error in connect()");
		ExitWithPause(1);
	}
	PrintLine("connect() done");

	char expression[bufferSize];
	
	int num1 = 0,
		num2 = 0;

	char opr = '\0';
	
	PrintLine("Enter Expression: (Like 2+2)");
	scanf("%d", &num1);
	scanf("%c", &opr);
	scanf("%d", &num2);

	MakeExpression(expression, num1, num2, opr);

	PrintLine("send()...");
	int sentSize = send(serverSocket, expression, strlen(expression), 0);

	if (sentSize == SOCKET_ERROR)
	{
		PrintLine("Error in send()");
		ExitWithPause(1);
	}
	PrintLine("send() done");

	char response[bufferSize];

	PrintLine("recv()...");
	int receiveLen = recv(serverSocket, response, bufferSize, 0);

	if (receiveLen == SOCKET_ERROR)
	{
		PrintLine("Error in recv()");
		ExitWithPause(1);
	}
	PrintLine("recv() done");

	response[receiveLen] = '\0';

	PrintLine("Response: %s", response);

	PrintLine("Exiting...");

	shutdown(serverSocket, SD_BOTH);
	closesocket(serverSocket);
	WSACleanup();

	ExitWithPause(0);
}